﻿using System.Collections.Generic;
using CodeParser.Tokens;

namespace CodeParser.Expressions
{
    public class AnnotationParser
        : ExpressionParser
    {

        public AnnotationParser()
        {
            BodyParsers = new List<ExpressionParser>();
        }

        public override Expression Parse(Token[] tokens, int index)
        {
            if (tokens[index].Value == "<")
            {
                var annotation = new Annotation {OpenBracket = tokens[index]};
                
                var closeIndex = ParseUtils.FindClosingBracket(tokens, index, "<", ">");
                if (closeIndex.HasValue)
                {
                    annotation.CloseBracket = tokens[closeIndex.Value];
                    annotation.TokenLength = closeIndex.Value - index + 1;
                }
                else
                {
                    annotation.TokenLength = tokens.Length - index;
                }
                annotation.Body = ParseSubExpression(tokens, index + 1, annotation.TokenLength - (closeIndex.HasValue? 2 : 1), BodyParsers);

                annotation.Add(new SingleToken() { Token = tokens[index] });
                if (annotation.Body != null) annotation.Add(annotation.Body);
                if (annotation.CloseBracket != null) annotation.Add(new SingleToken() { Token = tokens[index] });
                annotation.StringIndex = annotation.OpenBracket.Index;
                var lastToken = tokens[index + annotation.TokenLength - 1];
                annotation.StringLength = lastToken.Index + lastToken.Value.Length - annotation.StringIndex;

                return annotation;
            }
            return null;
        }

        public List<ExpressionParser> BodyParsers { get; set; }

    }
}
